<template>
  <div class="box">
    <el-button type="button" class="prevBtn" @click="prev()"
      >返回上一页</el-button
    >
    <div id="postTitle"></div>
    <!-- <button type="button"  @click="postEditorData">提交</button> -->

    <el-button type="button" class="btn" @click="dialogFormVisible = true"
      >发表</el-button
    >

    <el-dialog title="请填写博客相关信息" :visible.sync="dialogFormVisible">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        destroy-on-close="true"
      >
        <el-form-item label="博客标题" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="博客简介" prop="desc">
          <el-input type="textarea" v-model="ruleForm.desc"></el-input>
        </el-form-item>

        <el-form-item label="博客标签" prop="type">
          <div class="tagsList">
            <el-checkbox-group
              v-model="ruleForm.type"
              v-for="item in labals"
              v-bind:key="item.id"
            >
              <el-checkbox
                :label="item.tag"
                name="type"
                class="tagsItem"
              ></el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>

      <el-upload
        class="upload-img"
        action="http://localhost:8083/picture/uploadPicture"
        :on-remove="handleRemove"
        :data="titleInfo"
        list-type="picture"
        :auto-upload="false"
        :limit="1"
        :on-exceed="outlimit"
        :on-success="uploadResult(true)"
        :on-error="uploadResult(false)"
        ref="upload"
      >
        <el-button size="small" type="primary">点击上传博客封面图片</el-button>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm()">重置</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postBlog('ruleForm')"
          >提 交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  setLocalStorage,
  getLocalStorage,
  removeLocalStorage,
} from "@/util/local-storage.js";
import axios from "axios";
import E from "wangeditor";
import Loading from "element-ui";

export default {
  name: "postTitle",
  data() {
    return {
      editor: null,
      editorData: "",
      dialogFormVisible: false,
      onload: false,
      labals: [],
      titleInfo: {
        title_id: 0,
        blog_id: 0,
      },
      ruleForm: {
        name: "",
        type: [],
        desc: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入博客标题", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        desc: [{ required: true, message: "请填写博客简介", trigger: "blur" }],
        type: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个标签",
            trigger: "change",
          },
        ],
      },

    };
  },
  mounted() {
    const editor = new E("#postTitle");
    // 创建编辑器
    editor.config.height = 500;
    editor.config.zIndex = 500;
    editor.create();
    this.editor = editor;
  },
  methods: {
    prev() {
      console.log("this.$route.params.tagle:", this.$route.params.tagle);
      this.$router.replace({ name: this.$route.params.tagle });
    },
    postResult(res) {
      let i = this.postEditorData();
      console.log("i:", i);
      if (i && res) {
        this.$message({
          duration: 2000,
          message: "上传成功",
          center: true,
          type: "success",
        });

        this.resetForm();
        this.onload = false;
        this.dialogFormVisible = false;
        this.closeFullScreen(this.openFullScreen());
        this.$router.replace({ name: "Myblog" });
      } else {
        this.$message({
          duration: 2000,
          message: "上传失败",
          center: true,
          type: "error",
        });

        this.resetForm();
        this.onload = false;
        this.dialogFormVisible = false;
        this.closeFullScreen(this.openFullScreen());
        return;
      }
    },
    handleRemove() {
      this.$message({
        duration: 2000,
        message: "图片移除成功，可重新选择图片",
        center: true,
        type: "success",
      });
      return;
    },
    uploadResult(res) {
      if (this.onload) {
        this.postResult(res);
      }
    },
    resetForm() {
      this.$refs["ruleForm"].resetFields();
    },
    //提交表单和上传图片
    postBlog(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid);
        if (valid) {
          let header = {
            headers: {
              "MyBlog-Token": localStorage.getItem("Authorization"),
            },
          };

          if (this.$route.params.blogId) {
            let params = {
              blogId: this.$route.params.blogId,
              blogTitleHeader: this.ruleForm.name,
              blogTitleContent: this.ruleForm.desc,
              blogTitleLabel: this.ruleForm.type,
            };
            axios
              .post("http://localhost:8083/titles/modifyTitle", params, header)
              .then((res) => {
                if (res.data.errno != 0) {
                  this.$message({
                    duration: 2000,
                    message: res.data.errmsg,
                    center: true,
                    type: "error",
                  });
                  return;
                } else {
                  this.titleInfo.title_id = res.data.data.titleId;
                  console.log("---------------modifyTitleId:",this.titleInfo.title_id)
                  this.$refs.upload.submit();
                  this.onload = true;
                }
              });
          } else {
            let params = {
              blogTitleHeader: this.ruleForm.name,
              blogTitleContent: this.ruleForm.desc,
              blogTitleLabel: this.ruleForm.type,
            };
            axios
              .post("http://localhost:8083/titles/postTitle", params, header)
              .then((res) => {
                if (res.data.errno != 0) {
                  this.$message({
                    duration: 2000,
                    message: res.data.errmsg,
                    center: true,
                    type: "error",
                  });
                  return;
                } else {
                  this.titleInfo.title_id = res.data.data.titleId;
                  this.$refs.upload.submit();
                  this.onload = true;
                }
              });
          }
        } else {
          this.$message({
            duration: 2000,
            message: "请将信息填充完整",
            center: true,
            type: "error",
          });
          return;
        }
      });
    },
    outlimit() {
      this.$message({
        duration: 2000,
        message: "只能选择一张图片",
        center: true,
        type: "error",
      });
      return;
    },
    //Loading加载
    openFullScreen() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      return loading;
    },
    closeFullScreen(loading) {
      loading.close();
    },
    postEditorData() {
      console.log("this.editor.txt.html()",this.editor.txt.html());

      this.openFullScreen();
      if (this.$route.params.blogId) {
        let params = {
          blog: this.editor.txt.html(),
          blog_id: this.$route.params.blogId
        };
        return axios
          .post("http://localhost:8083/blog/updateBlog", params)
          .then((res) => {
            if (res.data.errno != 0) {
              this.closeFullScreen(this.openFullScreen());

              return false;
            } else {
              this.closeFullScreen(this.openFullScreen());

              return true;
            }
          });
      } else {
        let params = {
          blog: this.editor.txt.html(),
          title_id: this.titleInfo.title_id,
        };
        return axios
          .post("http://localhost:8083/blog/setBlog", params)
          .then((res) => {
            if (res.data.errno != 0) {
              this.closeFullScreen(this.openFullScreen());

              return false;
            } else {
              this.closeFullScreen(this.openFullScreen());

              return true;
            }
          });
      }
    },
    getLabal() {
      axios.get("http://localhost:8083/tag/getTags").then((res) => {
        this.labals = res.data.data.list;
      });
    },
    getBlogInfo(blogId) {
      console.log("this.$route.params.blog_id:", blogId);

      axios
        .get("http://localhost:8083/titles/getTitleAndBlog", {
          params: { id: blogId },
        })
        .then((res) => {
          if (res.data.errno != 0) {
            this.$message({
              duration: 2000,
              message: res.data.errmsg,
              center: true,
              type: "error",
            });
            return;
          } else {
            this.editor.txt.html(res.data.data.blog.blogBody);

            this.ruleForm.name = res.data.data.titles.blogTitleHeader;
            this.ruleForm.desc = res.data.data.titles.blogTitleContent;
            let arr = res.data.data.titles.blogTitleLabel;
            console.log("res:", res.data.data.titles.blogTitleLabel);
            let arrs = arr.substr(
              arr.indexOf("[") + 1,
              arr.lastIndexOf("]") - 1
            );
            console.log("arrs:", arrs);
            this.ruleForm.type = arrs.split(",");
            for(let i=0;i<this.ruleForm.type.length;i++){
              this.ruleForm.type[i]=this.ruleForm.type[i].trim();
            }
            
            console.log("this.ruleForm:", this.ruleForm);
          }
        });
    },
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy();
    this.editor = null;
  },

  created() {
    this.getLabal();

    if (this.$route.params.blogId) {
      this.getBlogInfo(this.$route.params.blogId);
    }
  },
};
</script>

<style>
.tagsItem {
  background-color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  padding: 10px;
  text-align: center;
}

.tagsList {
  display: flex;
  width: 100%;
  height: 150px;
  overflow-y: auto;
  flex-wrap: wrap;
  flex-direction: row;
}

.upload-img {
  margin-left: 3%;
}

.box {
  width: 1200px;
  margin: auto;
  position: relative;
  padding-top: 8%;
}

.editor {
  margin-top: -1px;
  border: 1px solid #ccc;
  min-height: 400px;
  height: auto;
}

.btn {
  position: relative;
  left: 85%;
  top: 10px;
  background-color: antiquewhite;
  width: 150px;
  height: 30px;
  padding: 5px 10px;
  cursor: pointer;
}

.prevBtn {
  position: relative;
  left: 85%;
  bottom: 10px;
  background-color: antiquewhite;
  width: 150px;
  height: 30px;
  padding: 5px 10px;
  cursor: pointer;
}

.btn:active {
  background-color: #fff;
  outline: none;
}
</style>
